// Copyright (c) 2008 Matthew Johnson
// Licensed under the MIT License (see license.txt)
package actionml.core {
	import actionml.Global; 
	
	import flash.display.DisplayObjectContainer;
	import flash.text.TextField;
	
	public class ObjectIterationMethods {
		public static function initialize() {
			Global.initializeExtension(ObjectIterationMethods, Object);
		}
		public static var instanceMethods:Object = {
			getNumChildren: function() {
				if ("numChildren" in this) {
					return this.numChildren;
				} else if (this is TextField) {
					return 0;
				} else if ("length" in this) {
					return this.length;
				} else {
					return 0;
				}
			},
			getChildAt: function(i:int) {
				if (this is DisplayObjectContainer) {
					return this.getChildAt(i);
				} else {
					return this[i];
				}
			},
			
			walkTree: function(f:Function, includeThis:Boolean = true) {
				if (includeThis) {
					f(this);
				}
				for (var i:int = 0; i < this.getNumChildren(); i++) {
					var child:* = this.getChildAt(i);
					if (child) {
						child.walkTree(f);
					}
				}			
			},
			mapTree: function(f:Function, includeThis:Boolean = true) {
				var r:Array = [];
				if (includeThis) {
					r.append(f(this));
				}
				for (var i:int = 0; i < this.getNumChildren(); i++) {
					var child:* = this.getChildAt(i);
					if (child) {
						r.append(child.mapTree(f));
					}
				}
				return r;
			},
			filterTree: function(f:Function, includeThis:Boolean = true) {
				var r:Array = [];
				if (includeThis && f(this)) {
					r.append(this);
				}
				for (var i:int = 0; i < this.getNumChildren(); i++) {
					var child:* = this.getChildAt(i);
					if (child) {
						r.append(child.filterTree(f));
					}
				}
				return r;
			}			
		};
	}
}